package com.wushi.lenovo.asia5b.app_push;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.mvp.base.BaseApplication;
import com.mvp.utils.ResString;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.other.PushBean;
import com.wushi.lenovo.asia5b.app_ui.other.activity.MainActivity;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2020/6/1.
 */
public class NotificationHelper {
    /**
     * 收到通知数据
     */
    public static void receive(PushBean inputBean) {
        //数据不能为空
        if (inputBean == null) {
            return;
        }
        Bitmap[] bitmaps = new Bitmap[2];//0:smallBitmap 1:bigBitmap
        //设置大图,小图
        Observable.just(inputBean)
                .map(new Function<PushBean, Integer>() {
                    @Override
                    public Integer apply(PushBean bean) throws Exception {
                        String smallImgUrl = bean.getSmallImageUrl();
                        if (!TextUtils.isEmpty(smallImgUrl)) {
                            bitmaps[0] = Glide.with(BaseApplication.sContext).asBitmap().load(smallImgUrl).submit().get();
                        }
                        String bigImgUrl = bean.getBigImageUrl();
                        if (!TextUtils.isEmpty(bigImgUrl)) {
                            bitmaps[1] = Glide.with(BaseApplication.sContext).asBitmap().load(bigImgUrl).submit().get();
                        }
                        return 1;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    showNotification(inputBean, bitmaps[0], bitmaps[1]);
                }, throwable -> {
                    throwable.printStackTrace();
                    showNotification(inputBean, bitmaps[0], bitmaps[1]);
                });

    }

    private static void showNotification(PushBean inputBean, Bitmap smallBitmap, Bitmap bigBitmap) {
        Context context = BaseApplication.sContext;
        String title = TextUtils.isEmpty(inputBean.getTitle()) ? "" : inputBean.getTitle();
        String body = TextUtils.isEmpty(inputBean.getBody()) ? "" : inputBean.getBody();
        String extendBody = inputBean.getExtendBody();
        String channelId = ResString.get(R.string.default_notification_channel_id);
        String channelName = "Asia5B message";
        //视图点击
        //避免使用序列化
        MyFirebaseMessagingService.bean = inputBean;
        Intent intent = new Intent(BaseApplication.sContext, MainActivity.class);
        intent.putExtra(FireBasePushHelper.channel_data, FireBasePushHelper.channel_data_value);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        PendingIntent pendingIntent = PendingIntent.getActivity(BaseApplication.sContext, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
        //todo 必须使用此创建对象,适配8.0(构造函数要求您提供一个通道ID。为了与Android 8.0（API级别26）及更高版本兼容，这是必需的，但较早版本会忽略。)
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context, channelId);
        //设置标题
        builder.setContentTitle(title);
        //设置内容
        builder.setContentText(body);
        //设置app icon
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //设置收缩图右边大的icon
        if (smallBitmap != null) {
            builder.setLargeIcon(smallBitmap);
        }
        //设置扩展图片
        if (bigBitmap != null) {
            builder.setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(bigBitmap)//todo 这是设置展开视图的大图
                    .bigLargeIcon(smallBitmap != null ? smallBitmap : bigBitmap));//todo 这是设置展开视图中顶部收缩图中右边的大icon
        } else if (!TextUtils.isEmpty(extendBody)) { //设置扩展文字
            builder.setStyle(new NotificationCompat.BigTextStyle().bigText(extendBody));
        }
        //其他信息
        builder.setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) BaseApplication.sContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        Notification notification = builder.build();
        notificationManager.notify(inputBean.getNotifyId() /* ID of notification */, notification);
        d("--->>>>>>>>---推送消息显示完毕");
    }

}
